package bb.lanxing.activity.team;

import static android.text.Spanned.SPAN_PARAGRAPH;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnButtonClickListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.tencent.qcloud.tuikit.tuicontact.bean.ContactItemBean;
import com.tencent.qcloud.tuikit.tuicontact.classicui.util.ContactStartChatUtils;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.team.TeamDetailBannerAdapter;
import bb.lanxing.ali.behavior.AppBehavior;
import bb.lanxing.chat.tencent.GenerateTestUserSig;
import bb.lanxing.chat.tencent.UserInfo;
import bb.lanxing.chat.tencent.utils.TUIUtils;
import bb.lanxing.model.data.TeamImageData;
import bb.lanxing.model.database.Event;
import bb.lanxing.model.database.User;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.BitmapHelper;
import bb.lanxing.util.DateUtil;
import bb.lanxing.util.DensityUtil;
import bb.lanxing.util.JsonUtil;
import bb.lanxing.view.UserAvatarView;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TeamDetailActivity extends BaseActivity {
    private final int INITIAL_STATUS = 0;
    private final int PENDING_APPROVAL_STATUS = 1;
    private final int APPROVAL_STATUS = 2;
    private final int QUITED_STATUS = 3;
    private final int KICK_OUT_STATUS = 4;
    private final int REJECTED_STATUS = 5;

    private static final int REQUEST_CODE_APPROVAL = 233;

    private Banner banner;
    private TeamDetailBannerAdapter bannerAdapter;

    private ImageView teamLeader;
    private LinearLayout memberContainer;
    private TextView memberCountView;

    private CardView approveLayout;
    private TextView approveText;
    private CardView statusLayout;
    private TextView statusText;

    private CardView locationLayout;
    private Switch locationSwitch;

    private TextView contentTV;

    private Button joinBtn;

    private Event mEvent;
    private Event mEventServer;

    private long mEventId = 0;

    private List<TeamImageData> bannerList = new ArrayList<>();
    private ArrayList<String> largeImageList = new ArrayList<>();

    private String teamLeaderHead = "";
    private ArrayList<String> teamHeadList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_detail);

        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());

        TextView title = findViewById(R.id.title);

        banner = findViewById(R.id.banner);
        bannerList.add(new TeamImageData(0, R.drawable.bg_event_item));
        bannerAdapter = new TeamDetailBannerAdapter(bannerList);
        banner.setAdapter(bannerAdapter);
        banner.setIndicator(new CircleIndicator(this));
        banner.setOnBannerListener((data, position) -> {
            Intent intent = new Intent(getActivity(), LargeImageActivity.class);
            intent.putStringArrayListExtra("images", largeImageList);
            intent.putExtra("currentImage", position);
            startActivity(intent);
        });

        TextView title1 = findViewById(R.id.title1);
        TextView time = findViewById(R.id.time);
        TextView location = findViewById(R.id.location);
        location.setOnClickListener(v -> {
            Intent intent = new Intent(this, TeamLocationActivity.class);
            intent.putExtra("StartAddr", mEventServer.getStartAddr());
            intent.putExtra("lat", mEventServer.getStartLat());
            intent.putExtra("lng", mEventServer.getStartLng());
            startActivity(intent);
        });
        TextView distance = findViewById(R.id.distance);
        TextView people = findViewById(R.id.people);
        TextView phone = findViewById(R.id.phone);
        phone.setMovementMethod(LinkMovementMethod.getInstance());
        TextView cost = findViewById(R.id.cost);
        TextView number = findViewById(R.id.number);
        TextView warning = findViewById(R.id.warning);
        warning.setOnClickListener(view -> new CircleDialog.Builder().setText(getString(R.string.event_notes_content))
                .setPositive(getString(R.string.dialog_btn_known), (OnButtonClickListener) null)
                .show(getActivity().getSupportFragmentManager()));

        teamLeader = findViewById(R.id.teamLeader);
        memberContainer = findViewById(R.id.memberContainer);
        memberCountView = findViewById(R.id.memberCountView);
        CardView memberLayout = findViewById(R.id.memberLayout);
        memberLayout.setOnClickListener(view -> onMemberClick());

        approveLayout = findViewById(R.id.approveLayout);
        approveLayout.setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), TeamApprovalActivity.class);
            intent.putExtra("event_id", mEventId);
            intent.putParcelableArrayListExtra("approveList", mEventServer.approveList);
            startActivityForResult(intent, REQUEST_CODE_APPROVAL);
        });
        approveText = findViewById(R.id.approveText);
        statusLayout = findViewById(R.id.statusLayout);
        statusText = findViewById(R.id.statusText);

        locationLayout = findViewById(R.id.locationLayout);
        locationSwitch = findViewById(R.id.locationSwitch);
        locationSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mEvent.setLocationSharing(1);
            } else {
                mEvent.setLocationSharing(0);
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put("locationSharing", mEvent.getLocationSharing());
            mEvent.update(contentValues);
            changeLocationShareStatus(App.getContext().getUserPhone());
        });

        contentTV = findViewById(R.id.content);

        joinBtn = findViewById(R.id.join_btn);
        joinBtn.setOnClickListener(view -> joinBtnClick());

        mEventId = getIntent().getLongExtra("event_id", 0L);
        mEvent = Event.getByEventId(mEventId);

        title.setText(mEvent.getTitle());
        String photoUrl = mEvent.getPhotoUrl();
        if (!TextUtils.isEmpty(photoUrl)) {
            bannerList = new ArrayList<>();
            try {
                JSONArray jSONArray = new JSONArray(mEvent.getPhotoUrl());
                for (int i = 0; i < jSONArray.length(); i++) {
                    String fileUrl = jSONArray.getJSONObject(i).optString("fileUrl");
                    if (!"".equals(fileUrl)) {
                        bannerList.add(new TeamImageData(1, fileUrl));
                        largeImageList.add(fileUrl);
                    }
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            bannerAdapter.setDatas(bannerList);
        }
        title1.setText(makeEventTitle(this, mEvent));
        time.setText(DateUtil.format(mEvent.getStartTime(), 10) + getString(R.string.to) +
                DateUtil.format(mEvent.getEndTime(), 10));
        location.setText(mEvent.getStartAddr());
        distance.setText(mEvent.getDistance() + " Km");
        people.setText(mEvent.getMemberCount() + " / " + mEvent.getMemberLimit() + getString(R.string.person));
        String phoneNumber = mEvent.getPhoneNumber();
        if (phoneNumber != null) {
            SpannableString spannableString = new SpannableString(phoneNumber);
            spannableString.setSpan(new URLSpan("tel:" + phoneNumber), 0, phoneNumber.length(), SPAN_PARAGRAPH);
            phone.setText(spannableString);
        }
        cost.setText(mEvent.getCost() + getString(R.string.person_money));
        number.setText(mEvent.getEventId() + getString(R.string.id));

        memberCountView.setText(mEvent.getMemberCount() + "");

        if (mEvent.getJoinStatus() == APPROVAL_STATUS) {
            locationLayout.setVisibility(View.VISIBLE);
        }
        if (mEvent.getLocationSharing() == 1) {
            locationSwitch.setChecked(true);
        }

        contentTV.setText(mEvent.getDescription());
        loadData();
    }

    private SpannableString makeEventTitle(Context context, Event event) {
        String levelName = Event.getLevelName(this, event.getLevel());
        int levelColor = Event.getLevelColor(event.getLevel());
        SpannableString spannableString = new SpannableString(levelName + "  " + event.getTitle());
        spannableString.setSpan(new ImageSpan(context, BitmapHelper.text2Bitmap(levelName, 14.0f, -1, levelColor, 4)), 0, 2, 17);
        return spannableString;
    }

    private void onMemberClick() {
        User user = App.getContext().getSigninUser();
        String userId = null;
        if (user == null) {
            App.getContext().userSignin();
            return;
        } else {
            userId = user.getPhone() + "";
        }
        if (mEventServer.getJoinStatus() != APPROVAL_STATUS) {
            toast(getString(R.string.please_join_event_first));
            return;
        }
        UserInfo userInfo = UserInfo.getInstance();
        userInfo.setUserId(userId);
        userInfo.setUserSig(GenerateTestUserSig.genTestUserSig(userId));
        TUILogin.login(getActivity(), GenerateTestUserSig.SDKAPPID, userInfo.getUserId(), userInfo.getUserSig(), TUIUtils.getLoginConfig(), new TUICallback() {
            @Override
            public void onError(final int code, final String desc) {
                getActivity().runOnUiThread(() -> ToastUtil.toastLongMessage("failed_login_tip, errCode = " + code + ", errInfo = " + desc));
            }

            @Override
            public void onSuccess() {
                if (user.getPhotoUrl() != null) {
                    V2TIMUserFullInfo info = new V2TIMUserFullInfo();
                    info.setFaceUrl(user.getPhotoUrl());
                    V2TIMManager.getInstance().setSelfInfo(info, new V2TIMCallback() {
                        @Override
                        public void onSuccess() {
                        }

                        @Override
                        public void onError(int code, String desc) {
                        }
                    });
                }
                UserInfo.getInstance().setAutoLogin(true);
                UserInfo.getInstance().setDebugLogin(true);
                ContactStartChatUtils.startChatActivity(mEventServer.getTencentImGroupId(), ContactItemBean.TYPE_GROUP, mEventServer.getTitle(), "Public");
            }
        });
    }

    private void loadData() {
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String string) {
                closePopWindow();
                try {
                    JSONObject eventJSON = new JSONObject(string).getJSONObject("event");
                    JSONObject groupJSON = new JSONObject(string).getJSONObject("group");
                    JSONArray approveJSONArray = new JSONObject(string).getJSONArray("ownerApprove");
                    mEventServer = Event.detailCreateByJson(eventJSON, groupJSON, approveJSONArray);
                    // 因本地存储总是创建一个新的，所以暂不存储。但是此处的mEventServer是从服务器拉取的，所以本地数据库id已丢失。
                    JSONArray jSONArray = new JSONObject(string).getJSONArray("memberInfo");
                    teamHeadList = new ArrayList<>();
                    for (int i = 0; i < jSONArray.length(); i++) {
                        JSONObject jSONObject = jSONArray.getJSONObject(i);
                        String avatar = JsonUtil.getStringValue("avatar", jSONObject);
                        if (JsonUtil.getBooleanValue("teamLeader", jSONObject)) {
                            teamLeaderHead = avatar;
                        } else {
                            teamHeadList.add(avatar);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                runOnUiThread(() -> {
                    Glide.with(context).load(teamLeaderHead).transform(new RoundedCorners(100)).into(teamLeader);
                    memberContainer.removeAllViews();
                    for (int i = 0; i < teamHeadList.size(); i++) {
                        UserAvatarView userAvatarView = new UserAvatarView(context);
                        LinearLayout.LayoutParams layoutParams = new LinearLayout
                                .LayoutParams(DensityUtil.dp2px(40.0f), DensityUtil.dp2px(40.0f));
                        layoutParams.setMargins(0, 0, DensityUtil.dp2px(8.0f), 0);
                        userAvatarView.setLayoutParams(layoutParams);
                        userAvatarView.setNormalAvatar(teamHeadList.get(i));
                        memberContainer.addView(userAvatarView);
                    }
                    memberCountView.setText(mEventServer.getMemberCount() + "");
                    updateUIStatus();
                    contentTV.setText(mEventServer.getDescription());
                });
            }
        };
        if (mEventServer == null) {
            showLoadingPopWindow("", false);
        }
        MyHttpClient.requestActivityDetail(biCiCallback, mEventId);
    }

    private void updateUIStatus() {
        if (mEventServer.getOwnerApprove() == 1) {
            if (mEventServer.isMine()) {
                if (mEventServer.approveList != null && !mEventServer.approveList.isEmpty()) {
                    approveLayout.setVisibility(View.VISIBLE);
                    approveText.setText(getString(R.string.teammates_waiting_approval)+"(" + mEventServer.approveList.size() + ")");
                }
            } else {
                statusLayout.setVisibility(View.VISIBLE);
                switch (mEventServer.getJoinStatus()) {
                    case INITIAL_STATUS:
                        statusText.setText(getString(R.string.not_in));
                        joinBtn.setText(R.string.event_detail_join);
                        break;
                    case PENDING_APPROVAL_STATUS:
                        statusText.setText(getString(R.string.wait_for_approval));
                        joinBtn.setText(getString(R.string.wait_for_review));
                        joinBtn.setClickable(false);
                        break;
                    case APPROVAL_STATUS:
                        statusText.setText(getString(R.string.pass_examination));
                        joinBtn.setText(R.string.event_detail_exit_event);
                        break;
                    case QUITED_STATUS:
                        statusText.setText(getString(R.string.already_left));
                        joinBtn.setText(getString(R.string.rejoin));
                        break;
                    case KICK_OUT_STATUS:
                        statusText.setText(getString(R.string.have_been_rejected));
                        joinBtn.setText(getString(R.string.rejoin));
                        break;
                    case REJECTED_STATUS:
                        statusText.setText(getString(R.string.fail_audit));
                        joinBtn.setText(getString(R.string.rejoin));
                        break;
                }
            }
        } else {
            if (!mEventServer.isMine()) {
                if (mEventServer.getJoinStatus() == APPROVAL_STATUS) {
                    joinBtn.setText(R.string.event_detail_exit_event);
                } else {
                    joinBtn.setText(R.string.event_detail_join);
                }
            }
        }
        if (mEventServer.getJoinStatus() == APPROVAL_STATUS) {
            locationLayout.setVisibility(View.VISIBLE);
        } else {
            locationLayout.setVisibility(View.GONE);
            locationSwitch.setChecked(false);
        }
        if (mEventServer.isMine()) {
            joinBtn.setText(R.string.event_detail_delete_event);
        } else {
            if (System.currentTimeMillis() > mEventServer.getEndTime()) {
                joinBtn.setText(R.string.event_detail_finished);
                joinBtn.setClickable(false);
            }
        }
    }

    private void joinBtnClick() {
        if (mEventServer.isMine()) {
            new CircleDialog.Builder().setTitle(getString(R.string.event_detail_delete_confirm))
                    .setText(getString(R.string.event_detail_delete_msg))
                    .setPositive(getString(R.string.confirm), v -> {
                        MyHttpClient.deleteActivity(new BiCiCallback() {
                            @Override
                            public void onResponseString(@NonNull String string) {
                                mEvent.delete();
                                toast(R.string.toast_delete_successful);
                                finish();
                            }
                        }, mEventId);
                        return true;
                    }).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                    .show(getActivity().getSupportFragmentManager());
        } else {
            if (mEventServer.getJoinStatus() == APPROVAL_STATUS) {
                new CircleDialog.Builder().setTitle(getString(R.string.event_detail_quit_confirm))
                        .setText(getString(R.string.event_detail_quit_msg))
                        .setPositive(getString(R.string.confirm), v -> {
                            MyHttpClient.quitActivity(new BiCiCallback() {
                                @Override
                                public void onResponseString(@NonNull String string) {
                                    loadData();
                                }
                            }, mEventId, App.getContext().getUserPhone());
                            return true;
                        }).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                        .show(getActivity().getSupportFragmentManager());
            } else {
                if (App.getContext().isUserSignin()) {
                    String userPhone = App.getContext().getUserPhone();
                    if (TextUtils.isEmpty(userPhone)) {
                        return;
                    }
                    if (App.getContext().getSigninUser().getTencentIm() == null || "0".equals(App.getContext().getSigninUser().getTencentIm())) {
                        new CircleDialog.Builder().setTitle(getString(R.string.main_team)).setText(getString(R.string.team_permission_content))
                                .setPositive(getString(R.string.apply), v -> {
                                    requestUserTencentImAccount(App.getContext().getSigninUser().getPhone());
                                    return true;
                                }).show(getActivity().getSupportFragmentManager());
                    } else {
                        joinEvent(userPhone);
                        AppBehavior.activity().join().trace(AppBehavior.getTraceId(getIntent())).item(String.valueOf(mEvent.getId())).submit();
                    }
                } else {
                    App.getContext().userSignin();
                }
            }
        }
    }

    private void requestUserTencentImAccount(String phone) {
        Call call = MyHttpClient.bindTencentIM(phone);
        showLoadingDialog(R.string.map_handling_share, true);
        Observable.create(new NetSubscribe(call)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.failed_apply));
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    toast(getString(R.string.applied_join));
                                    joinEvent(phone);
                                    AppBehavior.activity().join().trace(AppBehavior.getTraceId(getIntent())).item(String.valueOf(mEvent.getId())).submit();
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.failed_apply));
                        }
                    }
                });
    }

    private void joinEvent(String userPhone) {
        showMyProgressDialog(R.string.event_detail_joining);
        MyHttpClient.joinActivity(new BiCiCallback(this) {
            @Override
            public void onResponseString(@NonNull String string) {
                loadData();
            }
        }, mEventId, userPhone);
    }

    private void changeLocationShareStatus(String userPhone) {
        MyHttpClient.shareLocation(new BiCiCallback(this) {
            @Override
            public void onResponseString(@NonNull String string) {
            }
        }, mEventId, userPhone, mEvent.getLocationSharing());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_APPROVAL) {
            mEventServer.approveList = data.getParcelableArrayListExtra("approveList");
        }
    }
}